import _ from 'lodash';
import moment from 'moment';
import { message } from 'antd';
import * as XLSX from 'xlsx';
import { serverUrl } from '../../../../config/urlConfig';
import type { IOrginDealElementOptions } from './type';

export const USER_TYPE_DIC = [
  {
    value: '0',
    label: '交易中心',
  },
  {
    value: '1',
    label: '发电企业',
  },
  {
    value: '2',
    label: '用电企业',
  },
  {
    value: '3',
    label: '政府',
  },
  {
    value: '4',
    label: '供电公司',
  },
  {
    value: '5',
    label: '售电公司',
  },
];

export const xinjiangExportDic = [
  {
    code: 'stationName',
    name: '场站',
  },
  {
    code: 'powerPurchaserName',
    name: '购电方',
  },
  {
    code: 'userType',
    name: '用户类型',
  },
  {
    code: 'sellerPurchaserName',
    name: '售电方',
  },
  {
    code: 'tradeSequenceName',
    name: '交易序列',
  },
  {
    code: 'contractName',
    name: '合同名称',
  },
  {
    code: 'contractId',
    name: '合同编号',
  },
  {
    code: 'tag',
    name: '时段',
  },
  {
    code: 'contractPrice',
    name: '电价(元/MWh)',
  },
  {
    code: 'contractQuantity',
    name: '电量(MWh)',
  },
  {
    code: 'powerSourceType',
    name: '电源类型',
  },
  {
    code: 'month',
    name: '月份',
  },
  {
    code: 'contractSource',
    name: '来源',
  },
];

// 处理交易单元数据
export const getDealElementOptions = (data: IOrginDealElementOptions[]) => {
  const _settlemen: Record<string, any> = {};
  let dataObj: Record<string, any> = {};
  const modalData: any[] = data.map((m: IOrginDealElementOptions) => {
    const _children = m?.children?.map((item: IOrginDealElementOptions) => {
      const children = item?.children?.map((n) => ({
        ...n,
        title: n?.label,
        key: n?.value,
        parentKey: item?.id,
        regionId: m?.value2 || '',
      }));
      dataObj = { ...dataObj, ..._.groupBy(children, 'value') };
      _settlemen[item?.id ? item?.id : ''] = children;
      return { ...item, key: item?.id, title: item?.label || '', children, parentKey: m?.id };
    });

    return {
      ...m,
      title: m?.label || '',
      children: _children,
      key: m?.value || '',
      value: m.value,
      regionId: m.value2,
    };
  });
  return { modalData, value: _.flatten(Object.values(_settlemen)), dataObj };
};

// 初始日历数据
export const initValue = (value: any) => {
  return Number(moment(value).format('DD'));
};

// 生成数组
export const repeatMonth = () => {
  const arr = Array.from({ length: 31 }, (v, i) => ({
    label: i + 1,
    value: i + 1,
  }));
  return arr;
};

// 对象数组去重
export const uniqueFunc = (arr: any, uniId: string) => {
  const res = new Map();
  return arr.filter((item: any) => !res.has(item[uniId]) && res.set(item[uniId], 1));
};

// 判断该用户是否有权限
export const havePermissions = (buttonType: string, buttonPermissions: any) => {
  const hasSave =
    buttonPermissions?.filter((item: any) => item.menuCode === buttonType)?.length > 0;
  if (!hasSave) {
    message.info('请联系管理员获取相关权限');
    return false;
  } else {
    return true;
  }
};

// 读取本地excel文件
export const readWorkbookFromLocalFile = (file: any, callback: any) => {
  const reader = new FileReader();
  reader.onload = (e: any) => {
    const data = e.target.result;
    const workbook = XLSX?.read(data, { type: 'binary' });
    if (callback) callback(workbook);
  };
  reader.readAsBinaryString(file);
};

// 讲excel文件数据转化为json
export const readWorkbook = (workbook: any) => {
  const sheetNames = workbook.SheetNames; // 工作表名称集合
  const worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
  const excelJson = XLSX.utils.sheet_to_json(worksheet);
  return excelJson;
};

// 数据保留小数位
export const ToFixed = (data: any, persion = 3) => {
  if (!data) return data;
  const dot = String(data).indexOf('.');
  let num = Number(data);
  if (dot !== -1) {
    const dotCnt = String(data).substring(dot + 1, data.length);
    if (dotCnt.length > persion) {
      num = Number(Number(data).toFixed(persion));
    } else {
      num = Number(data);
    }
  }
  return num;
};

export const TIME_ENUM = (point: 96 | 24) => {
  const timeArr = new Array(point);
  const time = moment().startOf('date');
  const pointArray: string[] = [];
  if (point === 96) {
    _.forEach(timeArr, () => {
      time.add(15, 'minutes');
      const timeData = `${time.format('HHmm') === '0000' ? '2400' : time.format('HHmm')}`;
      pointArray.push(timeData);
    });
  } else {
    _.forEach(timeArr, () => {
      time.add(60, 'minutes');
      const timeData = `${time.format('HHmm') === '0000' ? '2400' : time.format('HHmm')}`;
      pointArray.push(timeData);
    });
  }
  return pointArray;
};

// 获取日期
export const getDate = (date: string, startDate?: string, endDate?: string) => {
  const _date = date || moment().format('YYYYMMDD');
  const nowDay = moment(_date).daysInMonth();
  let nowDayArr = Array.from({ length: nowDay }, (v, i) =>
    moment(_date).startOf('month').add(i, 'days').format('YYYYMMDD'),
  );
  if (startDate && endDate) {
    nowDayArr = nowDayArr.filter(
      (item) =>
        moment(item).endOf('day') >= moment(startDate).endOf('day') &&
        moment(endDate).endOf('day') >= moment(item).endOf('day'),
    );
  }
  return nowDayArr;
};

// 下载
export const handleDownload = async (
  obj: { annexPath?: string; annexId?: string },
  system: boolean,
) => {
  if (system) {
    // 下载
    // @ts-ignore
    const client = new OSS({
      region: 'oss-cn-beijing',
      accessKeyId: 'LTAI4G7w6tvFNPQ4q2hcHcD6',
      accessKeySecret: 'ZgALLEnmeqjjcTxlJnDEKKfJ6R5GUy',
      bucket: 'tianrun',
    });
    const url = client.signatureUrl(obj?.annexPath, {
      expires: 3600,
      response: {
        'content-disposition': 'attachment; filename="' + obj?.annexPath + '"',
      },
    });
    window.open(url);
  } else {
    window.open(`${serverUrl}/annex/annex/downLoadFile/${obj?.annexId}`);
  }
};

/**
 *  树形数组扁平化
 * @param {Array} arrs 树形数据
 * @param {string} childs 树形数据子数据的属性名,常用'children'
 * @param {Array} attrArr 需要提取的公共属性数组(默认是除了childs的全部属性)
 * @returns
 */
export const extractTree = (arrs: any, childs?: string, attrArr?: string[]) => {
  let attrList: any = [];
  if (!Array.isArray(arrs) && !arrs?.length) return [];
  if (typeof childs !== 'string') return [];
  if (!Array.isArray(attrArr) || (Array.isArray(attrArr) && !attrArr.length)) {
    attrList = Object.keys(arrs[0]);
    attrList.splice(attrList.indexOf(childs), 1);
  } else {
    attrList = attrArr;
  }
  const list: any = [];
  const getObj = (arr: any) => {
    arr.forEach((row: any) => {
      const obj: any = {};
      attrList.forEach((item: any) => {
        obj[item] = row[item];
      });
      list.push(obj);
      if (row[childs]) {
        getObj(row[childs]);
      }
    });
    return list;
  };
  return getObj(arrs);
};
